package com.bl.student.dao.repository;

import com.bl.student.common.enums.ArenaType;
import com.bl.student.common.enums.OnlineStatus;
import com.bl.student.dao.model.ArenaEntity;
import com.bl.student.dao.model.custom.ArenaSummary;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;

import java.util.List;

/**
 * Created by yujingyi on 2018/3/13.
 */
public interface ArenaRepository extends JpaRepository<ArenaEntity, String> {

    Page<ArenaEntity> findByStatusAndStartTimeAndTypeOrderByCreateTimeDesc(OnlineStatus status, Long date, ArenaType type, Pageable pageable);

    Page<ArenaEntity> findByStatusAndStartTimeAndTypeAndTitleContainingOrderByCreateTimeDesc(OnlineStatus status, Long date, ArenaType type, String title, Pageable pageable);

    Page<ArenaEntity> findByStatusAndTypeOrderByCreateTimeDesc(OnlineStatus status, ArenaType type, Pageable pageable);

    Page<ArenaEntity> findByStatusAndTypeAndTitleContainingOrderByCreateTimeDesc(OnlineStatus status, ArenaType type,String title, Pageable pageable);

    Page<ArenaEntity> findByCreatorIdAndTypeOrderByStartTimeDesc(String id, ArenaType type, Pageable pageable);

    List<ArenaEntity> findByCreatorIdAndTypeAndStatusOrderByStartTimeDesc(String id, ArenaType type, OnlineStatus status);

    List<ArenaEntity> findByCreatorIdAndTypeAndStatusAndStartTimeOrderByStartTimeDesc(String id, ArenaType type, OnlineStatus status,Long date);
    @Query(value = "SELECT * FROM ARENA WHERE STATUS = ?1 AND TYPE = ?2 GROUP BY START_TIME", nativeQuery = true)
    List<ArenaEntity> findByStatusAndTypeGroupByStartTime(String status,String type);

    @Query(value = "SELECT a.id as id, d.id as detail_id, d.collect as collect, a.weight as weight FROM ARENA a LEFT JOIN DETAIL d ON d.ID = a.DETAIL_ID " +
            "WHERE a.START_TIME = ?1 AND a.TYPE = ?2 AND a.status = ?3 /*#pageable*/",
            countQuery = "SELECT COUNT(*) FROM ARENA a LEFT JOIN DETAIL d ON d.ID = a.DETAIL_ID",
            nativeQuery = true)
    Page<ArenaSummary> findByStatusAndStartTimeAndTypeOrderByCollect(String startTime, String arenaType, String onlineStatus, Pageable pageable);

    @Modifying
    @Query(value = "UPDATE ARENA SET WEIGHT = ?2, STATUS = ?3 WHERE ID = ?1",
            nativeQuery = true)
    void updateArenaWeightAndStatus(String id, int weight, String status);

    long countByStatusAndStartTimeAndType(OnlineStatus status, Long startTime, ArenaType type);

    long countByStartTimeAndType(Long startTime, ArenaType type);

}
